home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / lib / python2.4 / site-packages / psyco / profiler.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2006-03-29  |  12KB  |  445 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. '''Psyco profiler (Python part).
  5.  
  6. The implementation of the non-time-critical parts of the profiler.
  7. See profile() and full() in core.py for the easy interface.
  8. '''
  9. import _psyco
  10. from support import *
  11. import math
  12. import time
  13. import types
  14. import atexit
  15.  
  16. try:
  17.     import thread
  18. except ImportError:
  19.     import dummy_thread as thread
  20.  
  21. current = None
  22. profilers = []
  23. logger = None
  24. go_lock = thread.allocate_lock()
  25.  
  26. def go(stop = 0):
  27.     global current
  28.     go_lock.acquire()
  29.     
  30.     try:
  31.         prev = current
  32.         if stop:
  33.             del profilers[:]
  34.         
  35.         if prev:
  36.             if profilers and profilers[0] is prev:
  37.                 return None
  38.             
  39.             prev.stop()
  40.             current = None
  41.         
  42.         for p in profilers[:]:
  43.             if p.start():
  44.                 current = p
  45.                 if logger:
  46.                     logger.write('%s: starting' % p.__class__.__name__, 5)
  47.                 
  48.                 return None
  49.                 continue
  50.     finally:
  51.         go_lock.release()
  52.  
  53.     if stop:
  54.         if logger:
  55.             logger.writefinalstats()
  56.         
  57.     else:
  58.         tag2bind()
  59.  
  60. atexit.register(go, 1)
  61.  
  62. def buildfncache(globals, cache):
  63.     if hasattr(types.IntType, '__dict__'):
  64.         clstypes = (types.ClassType, types.TypeType)
  65.     else:
  66.         clstypes = types.ClassType
  67.     for x in globals.values():
  68.         if isinstance(x, types.MethodType):
  69.             x = x.im_func
  70.         
  71.         if isinstance(x, types.FunctionType):
  72.             cache[x.func_code] = (x, '')
  73.             continue
  74.         if isinstance(x, clstypes):
  75.             for y in x.__dict__.values():
  76.                 if isinstance(y, types.MethodType):
  77.                     y = y.im_func
  78.                 
  79.                 if isinstance(y, types.FunctionType):
  80.                     cache[y.func_code] = (y, x.__name__)
  81.                     continue
  82.             
  83.     
  84.  
  85. function_cache = { }
  86.  
  87. def trytobind(co, globals, log = 1):
  88.     
  89.     try:
  90.         (f, clsname) = function_cache[co]
  91.     except KeyError:
  92.         buildfncache(globals, function_cache)
  93.         
  94.         try:
  95.             (f, clsname) = function_cache[co]
  96.         except KeyError:
  97.             if logger:
  98.                 logger.write('warning: cannot find function %s in %s' % (co.co_name, globals.get('__name__', '?')), 3)
  99.             
  100.             return None
  101.         except:
  102.             None<EXCEPTION MATCH>KeyError
  103.         
  104.  
  105.         None<EXCEPTION MATCH>KeyError
  106.  
  107.     if logger and log:
  108.         modulename = globals.get('__name__', '?')
  109.         if clsname:
  110.             modulename += '.' + clsname
  111.         
  112.         logger.write('bind function: %s.%s' % (modulename, co.co_name), 1)
  113.     
  114.     f.func_code = _psyco.proxycode(f)
  115.  
  116. if PYTHON_SUPPORT:
  117.     tagged_codes = []
  118.     
  119.     def tag(co, globals):
  120.         if logger:
  121.             
  122.             try:
  123.                 (f, clsname) = function_cache[co]
  124.             except KeyError:
  125.                 buildfncache(globals, function_cache)
  126.                 
  127.                 try:
  128.                     (f, clsname) = function_cache[co]
  129.                 except KeyError:
  130.                     clsname = ''
  131.                 except:
  132.                     None<EXCEPTION MATCH>KeyError
  133.                 
  134.  
  135.                 None<EXCEPTION MATCH>KeyError
  136.  
  137.             modulename = globals.get('__name__', '?')
  138.             if clsname:
  139.                 modulename += '.' + clsname
  140.             
  141.             logger.write('tag function: %s.%s' % (modulename, co.co_name), 1)
  142.         
  143.         tagged_codes.append((co, globals))
  144.         _psyco.turbo_frame(co)
  145.         _psyco.turbo_code(co)
  146.  
  147.     
  148.     def tag2bind():
  149.         if tagged_codes:
  150.             if logger:
  151.                 logger.write('profiling stopped, binding %d functions' % len(tagged_codes), 2)
  152.             
  153.             for co, globals in tagged_codes:
  154.                 trytobind(co, globals, 0)
  155.             
  156.             function_cache.clear()
  157.             del tagged_codes[:]
  158.         
  159.  
  160. else:
  161.     tag = trytobind
  162.     
  163.     def tag2bind():
  164.         pass
  165.  
  166.  
  167. class Profiler:
  168.     MemoryTimerResolution = 0.10299999999999999
  169.     
  170.     def run(self, memory, time, memorymax, timemax):
  171.         self.memory = memory
  172.         self.memorymax = memorymax
  173.         self.time = time
  174.         if timemax is None:
  175.             self.endtime = None
  176.         else:
  177.             self.endtime = time.time() + timemax
  178.         self.alarms = []
  179.         profilers.append(self)
  180.         go()
  181.  
  182.     
  183.     def start(self):
  184.         curmem = _psyco.memory()
  185.         memlimits = []
  186.         if self.memorymax is not None:
  187.             if curmem >= self.memorymax:
  188.                 if logger:
  189.                     logger.writememory()
  190.                 
  191.                 return self.limitreached('memorymax')
  192.             
  193.             memlimits.append(self.memorymax)
  194.         
  195.         if self.memory is not None:
  196.             if self.memory <= 0:
  197.                 if logger:
  198.                     logger.writememory()
  199.                 
  200.                 return self.limitreached('memory')
  201.             
  202.             memlimits.append(curmem + self.memory)
  203.             self.memory_at_start = curmem
  204.         
  205.         curtime = time.time()
  206.         timelimits = []
  207.         if self.endtime is not None:
  208.             if curtime >= self.endtime:
  209.                 return self.limitreached('timemax')
  210.             
  211.             timelimits.append(self.endtime - curtime)
  212.         
  213.         if self.time is not None:
  214.             if self.time <= 0.0:
  215.                 return self.limitreached('time')
  216.             
  217.             timelimits.append(self.time)
  218.             self.time_at_start = curtime
  219.         
  220.         
  221.         try:
  222.             self.do_start()
  223.         except error:
  224.             e = None
  225.             if logger:
  226.                 logger.write('%s: disabled by psyco.error:' % self.__class__.__name__, 4)
  227.                 logger.write('    %s' % str(e), 3)
  228.             
  229.             return 0
  230.  
  231.         if memlimits:
  232.             self.memlimits_args = (time.sleep, (self.MemoryTimerResolution,), self.check_memory, (min(memlimits),))
  233.             self.alarms.append(_psyco.alarm(*self.memlimits_args))
  234.         
  235.         if timelimits:
  236.             self.alarms.append(_psyco.alarm(time.sleep, (min(timelimits),), self.time_out))
  237.         
  238.         return 1
  239.  
  240.     
  241.     def stop(self):
  242.         for alarm in self.alarms:
  243.             alarm.stop(0)
  244.         
  245.         for alarm in self.alarms:
  246.             alarm.stop(1)
  247.         
  248.         del self.alarms[:]
  249.         if self.time is not None:
  250.             self.time -= time.time() - self.time_at_start
  251.         
  252.         if self.memory is not None:
  253.             self.memory -= _psyco.memory() - self.memory_at_start
  254.         
  255.         
  256.         try:
  257.             self.do_stop()
  258.         except error:
  259.             return 0
  260.  
  261.         return 1
  262.  
  263.     
  264.     def check_memory(self, limit):
  265.         if _psyco.memory() < limit:
  266.             return self.memlimits_args
  267.         
  268.         go()
  269.  
  270.     
  271.     def time_out(self):
  272.         self.time = 0.0
  273.         go()
  274.  
  275.     
  276.     def limitreached(self, limitname):
  277.         
  278.         try:
  279.             profilers.remove(self)
  280.         except ValueError:
  281.             pass
  282.  
  283.         if logger:
  284.             logger.write('%s: disabled (%s limit reached)' % (self.__class__.__name__, limitname), 4)
  285.         
  286.         return 0
  287.  
  288.  
  289.  
  290. class FullCompiler(Profiler):
  291.     
  292.     def do_start(self):
  293.         _psyco.profiling('f')
  294.  
  295.     
  296.     def do_stop(self):
  297.         _psyco.profiling('.')
  298.  
  299.  
  300.  
  301. class RunOnly(Profiler):
  302.     
  303.     def do_start(self):
  304.         _psyco.profiling('n')
  305.  
  306.     
  307.     def do_stop(self):
  308.         _psyco.profiling('.')
  309.  
  310.  
  311.  
  312. class ChargeProfiler(Profiler):
  313.     
  314.     def __init__(self, watermark, parentframe):
  315.         self.watermark = watermark
  316.         self.parent2 = parentframe * 2.0
  317.         self.lock = thread.allocate_lock()
  318.  
  319.     
  320.     def init_charges(self):
  321.         _psyco.statwrite(watermark = self.watermark, parent2 = self.parent2)
  322.  
  323.     
  324.     def do_stop(self):
  325.         _psyco.profiling('.')
  326.         _psyco.statwrite(callback = None)
  327.  
  328.  
  329.  
  330. class ActiveProfiler(ChargeProfiler):
  331.     
  332.     def active_start(self):
  333.         _psyco.profiling('p')
  334.  
  335.     
  336.     def do_start(self):
  337.         self.init_charges()
  338.         self.active_start()
  339.         _psyco.statwrite(callback = self.charge_callback)
  340.  
  341.     
  342.     def charge_callback(self, frame, charge):
  343.         tag(frame.f_code, frame.f_globals)
  344.  
  345.  
  346.  
  347. class PassiveProfiler(ChargeProfiler):
  348.     initial_charge_unit = _psyco.statread('unit')
  349.     reset_stats_after = 120
  350.     reset_limit = initial_charge_unit * 2.0 ** reset_stats_after
  351.     
  352.     def __init__(self, watermark, halflife, pollfreq, parentframe):
  353.         ChargeProfiler.__init__(self, watermark, parentframe)
  354.         self.pollfreq = pollfreq
  355.         self.progress = 2.0 ** (1.0 / halflife * pollfreq)
  356.  
  357.     
  358.     def reset(self):
  359.         _psyco.statwrite(unit = self.initial_charge_unit, callback = None)
  360.         _psyco.statreset()
  361.         if logger:
  362.             logger.write('%s: resetting stats' % self.__class__.__name__, 1)
  363.         
  364.  
  365.     
  366.     def passive_start(self):
  367.         self.passivealarm_args = (time.sleep, (1.0 / self.pollfreq,), self.do_profile)
  368.         self.alarms.append(_psyco.alarm(*self.passivealarm_args))
  369.  
  370.     
  371.     def do_start(self):
  372.         tag2bind()
  373.         self.init_charges()
  374.         self.passive_start()
  375.  
  376.     
  377.     def do_profile(self):
  378.         _psyco.statcollect()
  379.         if logger:
  380.             logger.dumpcharges()
  381.         
  382.         nunit = _psyco.statread('unit') * self.progress
  383.         if nunit > self.reset_limit:
  384.             self.reset()
  385.         else:
  386.             _psyco.statwrite(unit = nunit, callback = self.charge_callback)
  387.         return self.passivealarm_args
  388.  
  389.     
  390.     def charge_callback(self, frame, charge):
  391.         trytobind(frame.f_code, frame.f_globals)
  392.  
  393.  
  394.  
  395. class ActivePassiveProfiler(PassiveProfiler, ActiveProfiler):
  396.     
  397.     def do_start(self):
  398.         self.init_charges()
  399.         self.active_start()
  400.         self.passive_start()
  401.  
  402.     
  403.     def charge_callback(self, frame, charge):
  404.         tag(frame.f_code, frame.f_globals)
  405.  
  406.  
  407.  
  408. def psyco_settrace(*args, **kw):
  409.     '''This is the Psyco-aware version of sys.settrace().'''
  410.     result = original_settrace(*args, **kw)
  411.     go()
  412.     return result
  413.  
  414.  
  415. def psyco_setprofile(*args, **kw):
  416.     '''This is the Psyco-aware version of sys.setprofile().'''
  417.     result = original_setprofile(*args, **kw)
  418.     go()
  419.     return result
  420.  
  421.  
  422. def psyco_thread_stub(callable, args, kw):
  423.     _psyco.statcollect()
  424.     if kw is None:
  425.         return callable(*args)
  426.     else:
  427.         return callable(*args, **kw)
  428.  
  429.  
  430. def psyco_start_new_thread(callable, args, kw = None):
  431.     '''This is the Psyco-aware version of thread.start_new_thread().'''
  432.     return original_start_new_thread(psyco_thread_stub, (callable, args, kw))
  433.  
  434. original_settrace = sys.settrace
  435. original_setprofile = sys.setprofile
  436. original_start_new_thread = thread.start_new_thread
  437. sys.settrace = psyco_settrace
  438. sys.setprofile = psyco_setprofile
  439. if PYTHON_SUPPORT:
  440.     thread.start_new_thread = psyco_start_new_thread
  441.     if sys.modules.has_key('threading') and hasattr(sys.modules['threading'], '_start_new_thread'):
  442.         sys.modules['threading']._start_new_thread = psyco_start_new_thread
  443.     
  444.  
  445.